package com.kx.center.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.kx.center.entity.Brand;
import com.kx.center.service.BrandService;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kx.center.auth.Authentication;
import com.kx.center.entity.Account;
import com.kx.center.entity.Company;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.service.AccountService;
import com.kx.center.service.CompanyService;
import com.kx.center.util.Response;

@Controller
@RequestMapping("/company")
public class CompanyController extends CommonController{
	
	@Autowired
	CompanyService companyService;
	
	@Autowired
	AccountService accountService;

	@Autowired
	BrandService brandService;
	
	@RequestMapping(value = "add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String addCompany(HttpServletRequest request){
		
		String name = StringUtils.trimToEmpty(request.getParameter("name"));
		String corporation = StringUtils.trimToEmpty(request.getParameter("corporation"));
		String tel = StringUtils.trimToEmpty(request.getParameter("tel"));
		String email = StringUtils.trimToEmpty(request.getParameter("email"));
		
		if(StringUtils.isEmpty(name) || StringUtils.isEmpty(corporation) || StringUtils.isEmpty(tel) || StringUtils.isEmpty(email)){
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}
		
		Company company = new Company();
		company.setCompanyName(name);
		company.setCorporation(corporation);
		company.setPhone(tel);
		company.setEmail(email);
		company.setStatus(Company.STATUS_USE);
		
		boolean addStatus = companyService.addCompany(company);
		if(addStatus){
			return Response.success();
		}else{
			return Response.error(MessageCode.OPERATOR_FAIL, "数据库问题....傻逼了吧");
		}
	}
	
	/*
	 * 根据公司id查询详情
	 */
	@RequestMapping(value = "detail/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String companyDetail(HttpServletRequest request ,@PathVariable("id")String id){
		if(!NumberUtils.isDigits(id)){
			return Response.error(MessageCode.PARAMETER_WRONG);
		}
		Company company = companyService.findDetail(NumberUtils.toInt(id));
		HashMap<String, Object> data = new HashMap<>();
		data.put("data", company);
		return Response.success(data);
	}
	
	/*
	 * 更新公司信息
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String updateCompanyInfo(HttpServletRequest request){
		String idStr = request.getParameter("id");
		String companyName = request.getParameter("companyName");
		//公司法人
		String corporation = request.getParameter("corporation");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		
		if(!NumberUtils.isDigits(idStr)){
			return Response.error(MessageCode.PARAMETER_WRONG);
		}
		
		Company company = new Company();
		company.setId(NumberUtils.toInt(idStr));
		company.setCompanyName(companyName);
		company.setCorporation(corporation);
		company.setPhone(phone);
		company.setEmail(email);
		
		companyService.updateCompany(company);
		
		return Response.success("更新成功");
	}
	
	/*
	 * 删除公司 （更改公司的状态为失效）
	 */
	@RequestMapping(value = "delete/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String delete(HttpServletRequest request ,@PathVariable("id")String idStr){
		if(!NumberUtils.isDigits(idStr)){
			return Response.error(MessageCode.PARAMETER_WRONG);
		}
		
		companyService.deleteCompanyById(NumberUtils.toInt(idStr));
		
		return Response.success("删除成功");
	}
	
	
	@RequestMapping(value = "list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String listCompany(HttpServletRequest request){
		
		String pageNumStr = StringUtils.trimToEmpty(request.getParameter("page_num"));
		String pageSizeStr = StringUtils.trimToEmpty(request.getParameter("page_size"));
		
		int pageNum = 0;
		int paseCount = 10;
		
		try{
			pageNum = Integer.valueOf(pageNumStr);
			paseCount = Integer.valueOf(pageSizeStr);
		}catch(Exception e){
			
		}
		
		List<Company> companyList = companyService.getCompanyList(pageNum, paseCount, null);
		
		int hasNextPage = 0;
		if(companyList.size() == (paseCount+1)){
			companyList.remove(paseCount);
			hasNextPage = 1;
		}
		
		HashMap<String,Object> result = new HashMap<String,Object>();
		result.put("has_more", hasNextPage);
		result.put("company_list", companyList);
		result.put("current_page", pageNum);
		
		return Response.success(result);
		
	}
	
	@RequestMapping(value = "account/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String addCompanyAccount(HttpServletRequest request){

		Account userAccount = this.getCommonUserAccount(request);
		if(userAccount == null){
			return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
		}
		
		String name = StringUtils.trimToEmpty(request.getParameter("name"));
		String userName = StringUtils.trimToEmpty(request.getParameter("user_name"));
		String password = StringUtils.trimToEmpty(request.getParameter("password"));
		String email = StringUtils.trimToEmpty(request.getParameter("email"));
		String companyIdStr = StringUtils.trimToEmpty(request.getParameter("company_id"));
		
		
		if(StringUtils.isEmpty(name) || StringUtils.isEmpty(userName) || StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(companyIdStr)){
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}
		
		int companyId = 0;
		try{
			companyId = Integer.parseInt(companyIdStr);
		}catch(Exception e){
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}
		
		Account account = new Account();
		account.setDepartmentId(0);
		account.setEmail(email);
		account.setLoginName(userName);
		account.setPassword(password);
		account.setRoleId(1);
		account.setStatus(1);
		account.setSubscribe(false);
		account.setUserName(name);
		account.setCompanyId(companyId);
		account.setOperatorId(userAccount.getId());
		try{
			accountService.createAccount(account);
		}catch(Exception e){
			return Response.error(MessageCode.OPERATOR_FAIL, "添加账户失败");
		}
		return Response.success();
	}
	
	@RequestMapping(value = "account/list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String listCompanyAccount(HttpServletRequest request){
		
		String pageNumStr = StringUtils.trimToEmpty(request.getParameter("page_num"));
		String pageSizeStr = StringUtils.trimToEmpty(request.getParameter("page_size"));
		String companyIdStr = StringUtils.trimToEmpty(request.getParameter("company_id"));
		
		int pageNum = 0;
		int paseCount = 10;
		int companyId = 0;
		
		try{
			pageNum = Integer.valueOf(pageNumStr);
			paseCount = Integer.valueOf(pageSizeStr);
			companyId = Integer.valueOf(companyIdStr);
		}catch(Exception e){
			
		}
		if(companyId <= 0){
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}
		
		Company companyInfo = companyService.getCompanyById(companyId);
		if(companyInfo == null){
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}
		
		Map<String,Object> whereMap = new HashMap<String,Object>();
		whereMap.put("company_id", companyId);
		List<Account> companyAccountList = accountService.findAccountByCompany(pageNum, paseCount, whereMap);
		
		int hasNextPage = 0;
		if(companyAccountList.size() == (paseCount+1)){
			companyAccountList.remove(paseCount);
			hasNextPage = 1;
		}
		
		HashMap<String,Object> result = new HashMap<String,Object>();
		result.put("has_more", hasNextPage);
		result.put("account_list", companyAccountList);
		result.put("current_page", pageNum);
		result.put("company_info", companyInfo);
		
		return Response.success(result);
		
	}
	
	/*
	 * 修改账户
	 */
	
	
	
	/*
	 * 删除账户
	 */

	@RequestMapping(value = "brand/list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String listCompanyBrand(HttpServletRequest request){
		Account account = this.getCommonUserAccount(request);
		if(account == null){
			return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
		}

		int companyId = account.getCompanyId();
		Company companyInfo = this.getCommonUserCompany(companyId);

		String pageNumStr = StringUtils.trimToEmpty(request.getParameter("page_num"));
		String pageSizeStr = StringUtils.trimToEmpty(request.getParameter("page_size"));

		int pageNum = 0;
		int pageCount = 10;
		try{
			pageNum = Integer.valueOf(pageNumStr);
			pageCount = Integer.valueOf(pageSizeStr);
		}catch(Exception e){

		}


		List<Brand> brandList = brandService.getCompanyBrandList(companyId,pageNum,pageCount);
		int hasNextPage = 0;
		if(brandList.size() == (pageCount+1)){
			brandList.remove(pageCount);
			hasNextPage = 1;
		}

		HashMap<String,Object> result = new HashMap<String,Object>();
		result.put("has_more", hasNextPage);
		result.put("brand_list", brandList);
		result.put("current_page", pageNum);
		result.put("company_info", companyInfo);

		return Response.success(result);

	}
	
	/*
	 * 更新品牌
	 */
	@RequestMapping(value = "brand/update", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String updateBrand(HttpServletRequest request){
		
		String idStr = request.getParameter("id");
		if(!NumberUtils.isDigits(idStr)){
			return Response.error(MessageCode.PARAMETER_WRONG);
		}
		
		Account userAccount = this.getCommonUserAccount(request);
		if(userAccount == null){
			return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
		}
		
		String brandName = request.getParameter("brandName");
		
		Brand brand = new Brand();
		brand.setId(NumberUtils.toInt(idStr));
		brand.setBrandName(brandName);
		brand.setOperatorId(userAccount.getId());
		brandService.updateBrand(brand);
		return Response.success("更新成功");
	}
	
	/*
	 * 删除品牌
	 */
	@RequestMapping(value = "brand/delete/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String deleteBrand(HttpServletRequest request ,@PathVariable("id")String id){
		if(!NumberUtils.isDigits(id)){
			return Response.error(MessageCode.PARAMETER_WRONG);
		}
		
		brandService.deleteBrand(NumberUtils.toInt(id));
		return Response.success("删除成功");
	}

	@RequestMapping(value = "brand/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String addCompanyBrand(HttpServletRequest request){

		Account userAccount = this.getCommonUserAccount(request);
		if(userAccount == null){
			return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
		}

		String name = StringUtils.trimToEmpty(request.getParameter("name"));


		if(StringUtils.isEmpty(name)){
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}

		int companyId = userAccount.getCompanyId();

		Brand brand = new Brand();
		brand.setBrandName(name);
		brand.setCompanyId(companyId);
		brand.setOperatorId(userAccount.getId());
		brand.setStatus(1);

		try{
			int status = brandService.addCompanyBrand(companyId,brand);
			if(status <= 0){
				return Response.error(MessageCode.OPERATOR_FAIL, "添加品牌失败");
			}
		}catch(Exception e){
			return Response.error(MessageCode.OPERATOR_FAIL, "添加品牌失败");
		}
		return Response.success();
	}
	
}
